package com.xxl.config;

import com.xxl.dto.User;
import com.xxl.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * shiro身份认证、权限认证核心
 * @author xxl
 * @date 2023/3/14
 */
@SuppressWarnings("all")
public class UserRealm extends AuthorizingRealm {
    @Resource
    UserService userService;
    /**
     *  权限认证：在被shiro过滤器过滤之前会被调用
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User userInfo = (User) principalCollection.getPrimaryPrincipal();
        //设置当前用户权限
        info.addStringPermission(userInfo.getStatus());
        //设置用户为管理员,这里根据
        info.addRole(userInfo.getIdentity());
        return info;
    }
    /**
     *  身份认证:登录的时候会被调用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        User user = userService.findUserByName(userToken.getUsername());
        //如果查出的用户为空,控制器会报没有用户异常
        if (user == null) {return null;}
        //密码验证交给shiro
        return new SimpleAuthenticationInfo(user,user.getPwd(),user.getStatus());
    }
}
